package com.wander.rep.db4o;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;

public class Db4oHelper implements Parcelable {

	private ObjectContainer database; 
	private static final String DATABASE_NAME = "android.db4o";
	private static final int DATABASE_MODE = 0;
	private static Context ctx; 
	
	private String TAG = "Db40Helper";

	public Db4oHelper(Context context) {

		ctx=context;
		database=null;

	}

	/*
	 * Opens DB
	 */
	public void openDb()
	{
		try {
			if (database == null) {
				database = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(),
						db4oDBFullPath());
			}
		} catch (Exception ie) {
			Log.e(TAG, ie.toString());
		}


	}

	/*
	 * Returns Database Path
	 */
	public String db4oDBFullPath() {
		return ctx.getDir("data", DATABASE_MODE) + "/" + DATABASE_NAME;
	}

	/*
	 * Closes Database
	 */
	public void close() {
		if (this.database != null) {
			this.database.close();
		}
	}

	/*
	 * Returns ObjectContainer for Database querying
	 */
	public ObjectContainer getDatabaseSession() {

		if(database == null)
		{
			openDb();
		}
		return database.ext().openSession();
	}

	/*
	 * (non-Javadoc)
	 * @see android.os.Parcelable#describeContents()
	 */
	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
	 */
	@Override
	public void writeToParcel(Parcel arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
	
	/*
	 * 
	 */
	public static final Parcelable.Creator<Db4oHelper> CREATOR = new Creator<Db4oHelper>() {

	    public Db4oHelper createFromParcel(Parcel source) {

	        return new Db4oHelper(ctx);
	    }

	    public Db4oHelper[] newArray(int size) {

	        return new Db4oHelper[size];
	    }

	};

}